import { Inject, Injectable } from '@nestjs/common';
import { CellValue } from 'exceljs';
import fs from 'fs';
import stream from 'stream';
import { join } from 'path';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';
import puppeteer from 'puppeteer';

@Injectable()
export class ExcelService {
  // 显式注入HttpService
  @Inject(HttpService)
  private httpService: HttpService;

  async creteHtmlByData(data: { link: string; name: CellValue }[]) {
    return data.map(async (node) => {
      const html = await this.getContentByLink(node.link);
      let content = await this.getImgReplace(html);
      const path = join(process.cwd(), './Nest通关秘籍-爬取文件/');

      // 确保目录存在
      if (!fs.existsSync(path)) {
        fs.mkdirSync(path, { recursive: true });
      }

      fs.writeFileSync(
        `${path}/${node.name}.html`,
        `<!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <title></title>
          <style>
              code {
            display: inline-block;
          	background: #000;
            color: #fff;
            padding: 10px 10px;
            border-radius: 4px;
            line-height: 20px;
            }

          </style>
            </head>
            <body>
            ${content}
            </body>
            </html>`,
      );
      return node;
    });
  }

  /**
   * 获取内容并替换图片链接
   */
  private async getContentByLink(link: string) {
    try {
      // 使用Puppeteer启动浏览器
      const browser = await puppeteer.launch({
        headless: false, // 设置为true可以提高性能
        defaultViewport: {
          width: 0,
          height: 0,
        },
        // 如果仍然遇到路径问题，可以手动指定Chrome可执行文件路径
        executablePath:
          'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
      });

      const page = await browser.newPage();
      // 设置超时时间
      await page.setDefaultTimeout(30000);
      // 导航到页面
      await page.goto(link, { waitUntil: 'domcontentloaded' });
      // 获取content-container元素的内容
      let content = '';
      try {
        content = await page.$eval('.content-container', (el) => el.innerHTML);
        console.log(link, ': 成功获取content-container内容');
      } catch (error) {
        console.log(link, ': 未找到content-container元素，获取整个页面内容');
        content = await page.content();
      }

      // 关闭浏览器
      await browser.close();

      // 处理内容
      return content.replace(/\/\/liushuaiyang/g, 'https://liushuaiyang');
    } catch (error) {
      console.error('Puppeteer操作失败:', error.message);
    }
  }

  /**
   * 下载img 保存到 imgs 目录
   * @param content
   * @returns
   */
  private async getImgReplace(content) {
    const match = content.match(/https:\/\/\S{8,}png/g) || [];
    let index = 0;
    for await (let img of match) {
      // 确保目录存在
      const imgDir = join(process.cwd(), './Nest通关秘籍-爬取文件/imgs/');
      if (!fs.existsSync(imgDir)) {
        fs.mkdirSync(imgDir, { recursive: true });
      }

      const imgPath = join(
        process.cwd(),
        `./Nest通关秘籍-爬取文件/imgs/${img.replace(/https:\/\//g, '').replace(/[\,/]/g, '_')}`,
      );
      try {
        const response = await firstValueFrom(
          this.httpService.get(img, {
            responseType: 'stream',
          }),
        );
        await new Promise<void>((resolve, reject) => {
          stream.pipeline(
            response.data,
            fs.createWriteStream(imgPath),
            (err) => {
              index += 1;
              if (err) {
                console.error('下载图片失败:', err);
                reject(err);
              } else {
                if (index === match.length) {
                  console.log('download img all success', img);
                } else {
                  console.log('download img success', img);
                }
                resolve();
              }
            },
          );
        });
      } catch (error) {
        console.error('处理图片失败:', img, error.message);
      }
    }

    return content.replace(/https:\/\/\S{8,}png/g, (match) => {
      // 替换成本地的imgs/x.png 路径地址
      return `imgs/${match.replace(/https:\/\//g, '').replace(/[\,/]/g, '_')}`;
    });
  }
}
